const express = require('express');
const cors = require('cors');
const path = require('path');
const connectDB = require('./config/db');
const authenticateToken = require('./middleware/authenticateToken');

// 连接MongoDB数据库
connectDB();

// 导入路由
const cardsRouter = require('./routes/cards');
const connectionsRouter = require('./routes/connections');
const tabsRouter = require('./routes/tabs');
const authRouter = require('./routes/auth');

const app = express();
const PORT = process.env.PORT || 5000;

// 中间件
app.use(cors());
app.use(express.json());

// 路由
app.use('/api/cards', authenticateToken, cardsRouter);
app.use('/api/connections', authenticateToken, connectionsRouter);
app.use('/api/tabs', authenticateToken, tabsRouter);
app.use('/api/auth', authRouter);

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 根路由 - 提供index.html
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

module.exports = app;